<template>
  <div class="app-container">
    <!--查询栏-->
    <el-form :inline="true"
             v-if="advanced"
             :model="departmentQuery"
             class="demo-form-inline">

      <el-form-item label="科室名称" prop="name">
        <el-input v-model="departmentQuery.name" placeholder="请输入科室名称"></el-input>
      </el-form-item>

      <el-form-item label="科室介绍" prop="mobile">
        <el-input v-model="departmentQuery.introduce" placeholder="请输入科室介绍"></el-input>
      </el-form-item>

      <el-form-item label="科室地址" prop="mobile">
        <el-input v-model="departmentQuery.address" placeholder="请输入科室地址"></el-input>
      </el-form-item>

      <el-form-item label="科室联系电话" prop="mobile">
        <el-input v-model="departmentQuery.mobile" placeholder="请输入科室联系电话"></el-input>
      </el-form-item>

    </el-form>

    <!-- 操作 -->
    <div>
       <span class="table-page-search-submitButtons">

          <span class="submitButtons-left">
            <el-button size="small" type="success" @click="addDepartment" icon="el-icon-plus" plain>新增</el-button>
          </span>

          <span class="submitButtons-right">
            <el-button size="small" type="primary" @click="submitDepartmentQuery" icon="el-icon-search" plain>查询</el-button>
            <el-button size="small" @click="resetDepartmentQuery" icon="el-icon-refresh">重置</el-button>
            <a @click="toggleAdvanced" style="margin-left: 8px; color: #00BFFF; font-size: 14px">
              {{ advanced ? '收起' : '展开' }}
              <i :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" />
            </a>
          </span>

       </span>
    </div>

    <!--表格-->
    <el-table v-loading="isLoading"
              :data="departmentList"
              element-loading-text="数据加载中"
              border
              fit
              ref="multiplePublishActTable"
              highlight-current-row>

      <el-table-column prop="name" label="科室名称" width="120" align="center"></el-table-column>

      <el-table-column label="科室轮播图" width="260" align="center">
        <template slot-scope="scope">
          <img class="headImg" :src="scope.row.headImgs"/>
        </template>
      </el-table-column>

      <el-table-column prop="introduce" label="科室简介" width="400" align="center"></el-table-column>
      <el-table-column prop="address" label="办公地点" width="140" align="center"></el-table-column>
      <el-table-column prop="mobile" label="办公联系方式" width="180" align="center"></el-table-column>

      <el-table-column label="操作" align="center" width="212">

        <template slot-scope="scope">

          <el-button type="primary" @click="updateDepartment(scope.row)" size="mini" icon="el-icon-edit" round plain>修改</el-button>

          <el-button type="danger" size="mini" icon="el-icon-delete"
                     @click="removeDepartment(scope.row)" round plain>删除
          </el-button>

        </template>
      </el-table-column>

    </el-table>

    <!--分页器-->
    <el-pagination
      background
      :current-page="queryParams.currentPage"
      :page-size="queryParams.limit"
      :total="departmentListTotal"
      style="padding: 60px 0; text-align: center;"
      layout="total, prev, pager, next, jumper"
      @current-change="getDepartmentList"
    />

    <!--新增科室对话框-->
    <el-dialog :title="title" @close="addDepartmentCancel" :visible.sync="addVisible" width="800px" append-to-body>
      <el-form :model="addForm" ref="addForm" label-width="120px" :rules="updateDepartmentRules">

        <el-form-item label="科室名称" prop="name" width="100px">
          <el-input placeholder="请选择" v-model="addForm.name"/>
        </el-form-item>

        <el-form-item label="科室轮播图" prop="headImgs">
          <template slot-scope="scope">
            <el-upload
              class="avatar-uploader"
              :class="{hide:uploadDisabled}"
              action=""
              :http-request="httpRequestLogo"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              list-type="picture-card"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="currentPhotoList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>

            <el-dialog :visible.sync="dialogVisible" append-to-body>
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>

          </template>
        </el-form-item>

        <el-form-item label="科室简介" prop="introduce" width="100px">
          <el-input placeholder="请选择" v-model="addForm.introduce"/>
        </el-form-item>

        <el-form-item label="办公地点" prop="address" width="100px">
          <el-input placeholder="请选择" v-model="addForm.address"/>
        </el-form-item>

        <el-form-item label="办公联系方式" prop="mobile" width="100px">
          <el-input placeholder="请选择" v-model="addForm.mobile"/>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddDepartment">保存</el-button>
        <el-button @click="addDepartmentCancel">取 消</el-button>
      </div>

    </el-dialog>

    <!--修改科室对话框-->
    <el-dialog :title="title" @close="updateDepartmentCancel" :visible.sync="updateVisible" width="800px" append-to-body>
      <el-form :model="updateForm" ref="updateForm" label-width="120px" :rules="updateDepartmentRules">

        <el-form-item label="科室名称" prop="name" width="100px">
          <el-input placeholder="请选择" v-model="updateForm.name"/>
        </el-form-item>

        <el-form-item label="科室轮播图" prop="headImgs">
          <template slot-scope="scope">
            <el-upload
              class="avatar-uploader"
              :class="{hide:uploadDisabled}"
              action=""
              :http-request="httpRequestLogo"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="uploadSuccess"
              list-type="picture-card"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="currentPhotoList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>

            <el-dialog :visible.sync="dialogVisible" append-to-body>
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </template>

        </el-form-item>

        <el-form-item label="科室简介" prop="introduce" width="100px">
          <el-input placeholder="请选择" v-model="updateForm.introduce"/>
        </el-form-item>

        <el-form-item label="办公地点" prop="address" width="100px">
          <el-input placeholder="请选择" v-model="updateForm.address"/>
        </el-form-item>

        <el-form-item label="办公联系方式" prop="mobile" width="100px">
          <el-input placeholder="请选择" v-model="updateForm.mobile"/>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateDepartment">保存</el-button>
        <el-button @click="updateDepartmentCancel">取 消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
  import department from '@/api/yy/department'
  export default
  {
    name:"registrationList",
    data()
    {
      return {
        imageUrl:"",//科室图片
        dialogImageUrl: '',//当前放大图片的url
        dialogVisible: false,//放大图片是否显示
        currentPhotoList: [],//当前上传图片的名称

        departmentQuery:
        {
          name:"",
          introduce:"",
          address:"",
          mobile:"",
        },

        departmentList:[],//科室列表

        queryParams: //分页查询参数
        {
          currentPage: 1,
          limit: 4,
        },
        departmentListTotal:0,//科室列表总记录数

        advanced: false,//是否展开
        addForm: { //新增科室表单
          name:"",
          headImgs:"",
          introduce:"",
          address:"",
          mobile:"",
        },

        //会员卡的检查规则
        updateDepartmentRules:
          {
            name:
              [
                { required: true, message: "科室名称不能为空！", trigger: "change" }
              ],
            headImgs:
              [
                { required: true, message: "科室轮播图不能为空！", trigger: "change" }
              ],
            introduce:
              [
                { required: true, message: "科室简介不能为空！", trigger: "change" }
              ],
            address:
              [
                { required: true, message: "办公地点不能为空！", trigger: "change" }
              ],
            mobile:
              [
                { required: true, message: "科室联系方式不能为空！", trigger: "change" }
              ]
          },
        addVisible:false,//新增科室对话框是否可见
        updateVisible: false,//修改科室对话框是否可见
        updateForm: { //修改科室表单
          name:"",
          headImgs:"",
          introduce:"",
          address:"",
          mobile:"",
        },
        isLoading: false, //是否正在加载
        title: "",
      }
    },
    methods:
      {
        //科室图片上传
        httpRequestLogo(item)
        {
          const data = this.httpRequest(item);
        },
        //文件上传通用
        httpRequest(item)
        {
          //验证图片格式大小信息
          const isJPG = item.file.type == 'image/jpeg' || item.file.type == 'image/png';
          const isLt2M = item.file.size / 1024 / 1024 < 2;
          if (!isJPG)
          {
            this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
            this.imageUrl = null;
            this.currentPhotoList = [];
            return;
          }
          if (!isLt2M)
          {
            this.$message.error('上传图片大小不能超过 2MB!');
            this.imageUrl = null;
            this.currentPhotoList = [];
            return;
          }
          //图片格式大小信息没问题 执行上传图片的方法
          if (isJPG && isLt2M == true)
          {
            // post上传图片
            this.loading = true;
            //定义FormData对象 存储文件
            let mf = new FormData();
            //将图片文件放入mf
            mf.append('formFile', item.file);
            department.upLoadDepartmentImg(mf).then(response =>
            {
              if (response.code === 200)
              {
                this.$message.success(response.message);
                this.imageUrl = response.data.url;
                if(this.addVisible)//代表的是新增科室对话框
                {
                  this.addForm.headImgs = response.data.url;
                }
                if(this.updateVisible)//代表的是修改科室对话框
                {
                  this.updateForm.headImgs = response.data.url;
                }
                this.currentPhotoList = [{name: response.data.fileName, url: response.data.url}];
              } else
              {
                this.$message.error(response.message);
              }
            });
          }
        },
        //图片放大显示
        handlePictureCardPreview(file)
        {
          this.dialogImageUrl = file.url;
          this.dialogVisible = true;
        },
        handleExceed(files, fileList)
        {
          this.$message.warning("仅上传一张科室图片！");
        },
        //删除图片
        // deleteImages(imageKey)
        // {
        //   let that = this;
        //   department.deleteDepartmentImg(imageKey).then((response)=>
        //   {
        //     if(response.code === 200)
        //     {
        //       this.$message.success("删除成功!");
        //     }else
        //     {
        //       this.$message.error("删除失败!");
        //     }
        //   }).catch(error =>
        //   {
        //     this.isLoading = false;
        //     that.$message.error(error);
        //   });
        // },
        handleRemove(file)/*移除照片*/
        {
          let that = this;
          // let imageKey = {url:this.imageUrl};
          // this.deleteImages(imageKey);
          // this.imageUrl = '';
          if(this.addVisible)//代表的是新增科室对话框
          {
            this.addForm.headImgs = '';
          }
          if(this.updateVisible)//代表的是修改科室对话框
          {
            this.updateForm.headImgs = '';
          }
          this.currentPhotoList = [];

        },

        //查询科室
        submitDepartmentQuery()
        {
          if(!this.advanced)
          {
            this.advanced = !this.advanced;
          }
          this.getDepartmentList();
        },
        //重置科室查询参数
        resetDepartmentQuery()
        {
          this.departmentQuery =
          {
            name:"",
            introduce:"",
            address:"",
            mobile:"",
          };
          this.getDepartmentList();
        },

        //获取科室列表
        getDepartmentList(currentPage = 1)
        {
          let that = this;
          this.queryParams.currentPage = currentPage;
          this.isLoading = true;
          department.pageDepartmentCondition(this.queryParams.currentPage,this.queryParams.limit,this.departmentQuery)
            .then(response=>
            {
              this.departmentList = response.data.rows;
              this.departmentListTotal = response.data.total;
              this.isLoading = false;
            }).catch(error => {
            this.isLoading = false;
            that.$message.error(error);})
        },
        //打开新增科室对话框
        addDepartment()
        {
          this.addVisible = true;
          this.title="新增科室";
        },
        //新增科室
        submitAddDepartment()
        {
          this.$refs['addForm'].validate((valid) =>
          {
            if(valid)
            {
              department.addDepartment(this.addForm).then((response)=>
              {
                if(response.code === 200)
                {
                  this.$message.success("新增成功!");
                }else
                {
                  this.$message.error("新增失败!");
                }
              });
              this.addVisible = false;
              this.title="";
              this.addForm =
                {
                  name:"",
                  headImgs:"",
                  introduce:"",
                  address:"",
                  mobile:"",
                };
              this.getDepartmentList();
            }
          });
        },
        //新增科室对话框取消
        addDepartmentCancel()
        {
          this.addVisible= false;
          this.addForm =
            {
              name:"",
              headImgs:"",
              introduce:"",
              address:"",
              mobile:"",
            };
          this.title="";
        },
        /*query展开和收起*/
        toggleAdvanced()
        {
          this.advanced = !this.advanced;
        },
        //删除科室
        removeDepartment(row)
        {
          let id = row.id;
          let that = this;
          that.$confirm("是否确认删除"+row.name+"?").then(function()
          {
            // let imageKey = {url:row.headImgs};
            // that.deleteImages(imageKey);
            department.deleteDepartmentById(id).then((response)=>
            {
              if(response.code === 200)
              {
                that.$message.success("删除成功！");
                that.getDepartmentList();
              }else
              {
                that.$message.error("删除失败！");
              }
            }).catch(error=> {
              console.log(error)
            })
          })
        },

        //点击修改会员卡对话框
        updateDepartment(row)
        {
          this.updateVisible = true;
          this.title="修改科室";
          this.updateForm.id = row.id;
          this.updateForm.name = row.name;

          this.imageUrl = row.headImgs;
          this.currentPhotoList = [{name: row.name, url: row.headImgs}];

          this.updateForm.headImgs = row.headImgs;

          this.updateForm.introduce = row.introduce;
          this.updateForm.address = row.address;
          this.updateForm.mobile = row.mobile;
        },

        //提交会员卡的修改
        submitUpdateDepartment()
        {
          this.$refs['updateForm'].validate((valid) =>
          {
            if(valid)
            {
              department.updateDepartment(this.updateForm).then((response)=>
              {
                if(response.code === 200)
                {
                  this.$message.success("修改成功!");
                  this.getDepartmentList();
                }else
                {
                  this.$message.error("修改失败!");
                }
              });
              this.updateVisible = false;
              this.title="";
              this.updateForm =
                {
                  name:"",
                  headImgs:"",
                  introduce:"",
                  address:"",
                  mobile:"",
                };
              this.getDepartmentList();
            }
          });
        },

        //关闭会员卡的修改
        updateDepartmentCancel()
        {
          this.updateVisible = false;
          this.title="";
          this.updateForm =
            {
              name:"",
              headImgs:"",
              introduce:"",
              address:"",
              mobile:"",
            };
        },

      },
    computed:
      {
        uploadDisabled()
        {
          return this.currentPhotoList.length > 0;
        },
      },
    created()
    {
      this.getDepartmentList();
    }
  }
</script>

<style>
  .table-page-search-submitButtons
  {
    height: 50px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
  .headImg
  {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .hide .el-upload--picture-card {
    display: none;
  }
</style>

